<template>
  <div class="space-y-6">
    <!-- 统计卡片 -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
      <div class="bg-white rounded-lg shadow-sm p-6 border border-gray-200">
        <div class="flex items-center">
          <div class="flex-shrink-0">
            <div class="w-12 h-12 bg-blue-100 rounded-lg flex items-center justify-center">
              <i class="fas fa-users text-blue-600 text-xl"></i>
            </div>
          </div>
          <div class="ml-4">
            <p class="text-sm font-medium text-gray-500">总用户数</p>
            <p class="text-2xl font-semibold text-gray-900">{{ stats.userCount }}</p>
          </div>
        </div>
      </div>

      <div class="bg-white rounded-lg shadow-sm p-6 border border-gray-200">
        <div class="flex items-center">
          <div class="flex-shrink-0">
            <div class="w-12 h-12 bg-green-100 rounded-lg flex items-center justify-center">
              <i class="fas fa-book text-green-600 text-xl"></i>
            </div>
          </div>
          <div class="ml-4">
            <p class="text-sm font-medium text-gray-500">图书总数</p>
            <p class="text-2xl font-semibold text-gray-900">{{ stats.bookCount }}</p>
          </div>
        </div>
      </div>

      <div class="bg-white rounded-lg shadow-sm p-6 border border-gray-200">
        <div class="flex items-center">
          <div class="flex-shrink-0">
            <div class="w-12 h-12 bg-yellow-100 rounded-lg flex items-center justify-center">
              <i class="fas fa-shopping-cart text-yellow-600 text-xl"></i>
            </div>
          </div>
          <div class="ml-4">
            <p class="text-sm font-medium text-gray-500">订单总数</p>
            <p class="text-2xl font-semibold text-gray-900">{{ stats.orderCount }}</p>
          </div>
        </div>
      </div>

      <div class="bg-white rounded-lg shadow-sm p-6 border border-gray-200">
        <div class="flex items-center">
          <div class="flex-shrink-0">
            <div class="w-12 h-12 bg-purple-100 rounded-lg flex items-center justify-center">
              <i class="fas fa-dollar-sign text-purple-600 text-xl"></i>
            </div>
          </div>
          <div class="ml-4">
            <p class="text-sm font-medium text-gray-500">总销售额</p>
            <p class="text-2xl font-semibold text-gray-900">¥{{ (stats.totalSales || 0).toLocaleString() }}</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 图表区域 -->
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
      <!-- 销售趋势图 -->
      <div class="bg-white rounded-lg shadow-sm p-6 border border-gray-200">
        <h3 class="text-lg font-medium text-gray-900 mb-4">销售趋势</h3>
        <div ref="salesTrendChart" class="h-64"></div>
      </div>

      <!-- 分类销售占比 -->
      <div class="bg-white rounded-lg shadow-sm p-6 border border-gray-200">
        <h3 class="text-lg font-medium text-gray-900 mb-4">分类销售占比</h3>
        <div ref="categoryPieChart" class="h-80"></div>
      </div>
    </div>

    <!-- 最新订单和热门图书 -->
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
      <!-- 最新订单 -->
      <div class="bg-white rounded-lg shadow-sm border border-gray-200">
        <div class="px-6 py-4 border-b border-gray-200">
          <h3 class="text-lg font-medium text-gray-900">最新订单</h3>
        </div>
        <div class="p-6">
          <div class="space-y-4">
            <div v-for="order in recentOrders" :key="order.id" class="flex items-center justify-between">
              <div>
                <p class="text-sm font-medium text-gray-900">订单 #{{ order.orderNo }}</p>
                <p class="text-sm text-gray-500">{{ order.userName }}</p>
              </div>
              <div class="text-right">
                <p class="text-sm font-medium text-gray-900">¥{{ order.amount }}</p>
                <p class="text-sm text-gray-500">{{ formatDate(order.createdAt) }}</p>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 热门图书 -->
      <div class="bg-white rounded-lg shadow-sm border border-gray-200">
        <div class="px-6 py-4 border-b border-gray-200">
          <h3 class="text-lg font-medium text-gray-900">热门图书</h3>
        </div>
        <div class="p-6">
          <div class="space-y-4">
            <div v-for="book in popularBooks" :key="book.id" class="flex items-center">
              <img
                :src="getImageUrl(book.cover)"
                :alt="book.title"
                class="w-12 h-16 object-cover rounded border border-gray-200"
                @error="handleImageError"
              >
              <div class="ml-4 flex-1">
                <p class="text-sm font-medium text-gray-900">{{ book.title }}</p>
                <p class="text-sm text-gray-500">{{ book.author }}</p>
              </div>
              <div class="text-right">
                <p class="text-sm font-medium text-gray-900">销量: {{ book.sales }}</p>
                <p class="text-sm text-gray-500">¥{{ book.price }}</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, onUnmounted } from 'vue'
import { adminAPI } from '@/api/admin.js'
import * as echarts from 'echarts'

const stats = ref({
  userCount: 0,
  bookCount: 0,
  orderCount: 0,
  totalSales: 0
})

const recentOrders = ref([])
const popularBooks = ref([])

// 图表相关
const salesTrendChart = ref(null)
const categoryPieChart = ref(null)
let salesTrendChartInstance = null
let categoryPieChartInstance = null

const formatDate = (dateString) => {
  return new Date(dateString).toLocaleDateString('zh-CN')
}

// 获取图片URL
const getImageUrl = (url) => {
  if (!url) return ''

  // 如果是完整的URL，直接返回
  if (url.startsWith('http')) {
    return url
  }

  // 如果是上传的文件路径
  if (url.startsWith('/uploads/')) {
    return `http://localhost:8081/api${url}`
  }

  // 如果是静态资源路径
  if (url.startsWith('/assets/')) {
    return `http://localhost:8081/api${url}`
  }

  // 其他情况，添加API前缀
  return `/api${url}`
}

// 图片加载错误处理
const handleImageError = (event) => {
  console.error('图片加载失败:', event.target.src)
  // 设置默认图片
  event.target.src = ''
}

// 初始化销售趋势图表
const initSalesTrendChart = async () => {
  if (!salesTrendChart.value) return

  salesTrendChartInstance = echarts.init(salesTrendChart.value)

  try {
    // 获取销售趋势数据
    const response = await adminAPI.getSalesTrend()
    const trendData = response.data || {}

    const option = {
      title: {
        show: false
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross',
          label: {
            backgroundColor: '#6a7985'
          }
        }
      },
      legend: {
        data: ['销售额', '订单数']
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: [
        {
          type: 'category',
          boundaryGap: false,
          data: trendData.months || []
        }
      ],
      yAxis: [
        {
          type: 'value',
          name: '销售额(元)',
          position: 'left',
          axisLabel: {
            formatter: '{value}'
          }
        },
        {
          type: 'value',
          name: '订单数',
          position: 'right',
          axisLabel: {
            formatter: '{value}'
          }
        }
      ],
      series: [
        {
          name: '销售额',
          type: 'line',
          smooth: true,
          areaStyle: {
            opacity: 0.3
          },
          data: trendData.salesData || [],
          itemStyle: {
            color: '#3b82f6'
          }
        },
        {
          name: '订单数',
          type: 'line',
          smooth: true,
          yAxisIndex: 1,
          data: trendData.orderData || [],
          itemStyle: {
            color: '#10b981'
          }
        }
      ]
    }

    salesTrendChartInstance.setOption(option)
  } catch (error) {
    console.error('加载销售趋势数据失败:', error)
  }
}

// 初始化分类销售占比图表
const initCategoryPieChart = async () => {
  if (!categoryPieChart.value) return

  categoryPieChartInstance = echarts.init(categoryPieChart.value)

  try {
    // 获取分类销售数据
    const response = await adminAPI.getCategorySales()
    const categoryData = response.data || []

    // 优化的颜色搭配，参考图片风格
    const colors = [
      '#4472C4', // 蓝色 - 电商行业
      '#E15759', // 红色 - 交通出行
      '#70AD47', // 绿色 - 电子电器
      '#9966CC', // 紫色 - 网络通讯
      '#4BACC6', // 青色 - 银行金融保险
      '#F79646', // 橙色 - 房地产行业
      '#8064A2', // 深紫 - 教育培训
      '#C5504B', // 深红 - 汽车行业
      '#9BBB59', // 浅绿 - 快递物流
      '#8C6239', // 棕色 - 健身美容行业
      '#D99694', // 粉色 - 商超
      '#B2DF8A'  // 浅绿 - 其他
    ]

    const option = {
      title: {
        show: false
      },
      tooltip: {
        trigger: 'item',
        formatter: function(params) {
          return `${params.seriesName}<br/>${params.name}: ${params.value} (${params.percent}%)`
        },
        backgroundColor: 'rgba(0,0,0,0.8)',
        borderColor: '#ccc',
        borderWidth: 1,
        textStyle: {
          color: '#fff',
          fontSize: 12
        }
      },
      legend: {
        type: 'scroll',
        orient: 'vertical',
        right: '5%',
        top: 'center',
        itemWidth: 12,
        itemHeight: 12,
        itemGap: 8,
        textStyle: {
          fontSize: 11,
          color: '#333'
        },
        data: categoryData.map(item => item.name) || []
      },
      series: [
        {
          name: '销售占比',
          type: 'pie',
          radius: ['30%', '75%'],
          center: ['40%', '50%'],
          avoidLabelOverlap: true,
          itemStyle: {
            borderRadius: 2,
            borderColor: '#fff',
            borderWidth: 1
          },
          label: {
            show: true,
            position: 'outside',
            formatter: function(params) {
              return `${params.name}\n${params.percent}%`
            },
            fontSize: 10,
            color: '#333',
            lineHeight: 14
          },
          labelLine: {
            show: true,
            length: 8,
            length2: 5,
            smooth: 0.2,
            lineStyle: {
              color: '#999',
              width: 1
            }
          },
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            },
            label: {
              fontSize: 12,
              fontWeight: 'bold'
            }
          },
          data: categoryData.map((item, index) => ({
            value: item.value,
            name: item.name,
            itemStyle: { color: colors[index % colors.length] }
          }))
        }
      ]
    }

    categoryPieChartInstance.setOption(option)
  } catch (error) {
    console.error('加载分类销售数据失败:', error)
  }
}

// 处理窗口大小变化
const handleResize = () => {
  if (salesTrendChartInstance) {
    salesTrendChartInstance.resize()
  }
  if (categoryPieChartInstance) {
    categoryPieChartInstance.resize()
  }
}

// 销毁图表实例
const destroyCharts = () => {
  if (salesTrendChartInstance) {
    salesTrendChartInstance.dispose()
    salesTrendChartInstance = null
  }
  if (categoryPieChartInstance) {
    categoryPieChartInstance.dispose()
    categoryPieChartInstance = null
  }
}

const loadDashboardData = async () => {
  try {
    // 加载统计数据
    const statsResponse = await adminAPI.getDashboardStats()
    stats.value = statsResponse.data || {}

    // 加载最近订单
    const ordersResponse = await adminAPI.getRecentOrders()
    recentOrders.value = (ordersResponse.data || []).map(order => ({
      id: order.id,
      orderNo: order.orderNo,
      userName: order.receiverName || '未知用户',
      amount: order.actualAmount || 0,
      createdAt: order.createdAt
    }))

    // 加载热门图书
    const booksResponse = await adminAPI.getPopularBooks()
    popularBooks.value = booksResponse.data || []

    // 初始化图表
    await nextTick()
    await initSalesTrendChart()
    await initCategoryPieChart()
  } catch (error) {
    console.error('加载仪表盘数据失败:', error)
  }
}

onMounted(() => {
  loadDashboardData()
  // 监听窗口大小变化
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  // 移除事件监听器
  window.removeEventListener('resize', handleResize)
  // 销毁图表实例
  destroyCharts()
})
</script>
